package cn.mdmm.service.impl.type;

import java.util.ArrayList;
import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.TreeMap;

import javax.annotation.PostConstruct;

import org.apache.commons.lang.StringUtils;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import cn.mdmm.entity.response.ResponseBodyToOne;
import cn.mdmm.entity.type.TypeInfoModel;
import cn.mdmm.entity.type.dto.TypeTree;
import cn.mdmm.entity.type.request.TypeRequest;
import cn.mdmm.mapper.type.TypeInfoMapper;
import cn.mdmm.service.type.TypeInfoService;
import cn.modoumama.common.exception.RequiredException;
import cn.modoumama.common.response.Response;
import cn.modoumama.service.base.impl.BaseServiceImpl;


/**
* 类名称：TypeInfo对象定义<br>
* 类描述：新闻类别业务实现类<br>
* 类生产方式：工具自动生成代码<br>
* 创建人：dengqiang<br>
* 创建时间：2017-06-04 20:04:27<br>
* 修改人：  <br>
* 修改时间：<br>
* 修改备注：<br>
* @version   V1.0
*/

@Service
@Transactional
public class TypeInfoServiceImpl extends BaseServiceImpl<TypeInfoModel,Integer> implements TypeInfoService{
	public static Map<String, TypeInfoModel> allType = new HashMap<>();
	public static Map<String, TypeInfoModel> allEnglishType = new HashMap<>();
	public static List<TypeInfoModel> topTypes = new ArrayList<>();
	
	@Autowired
	public void setMapper(TypeInfoMapper genericMapper) {
		super.setGenericMapper(genericMapper);
	}

	//------------------请在此添加自定义方法（开始）------------------
	
	@PostConstruct
	@Override
	public void init() {
		allType = new HashMap<>();
		topTypes = new ArrayList<>();
		Map<String, Object> condititon = new HashMap<String, Object>();
		condititon.put("orderByClause", "`ORDER`");
		List<TypeInfoModel> types = findModelsByCondition(condititon);
		
		for (TypeInfoModel type : types) {
			if(type.getPid()==0){
				topTypes.add(type);
			}
			allType.put(type.getId().toString(), type);
			allEnglishType.put(type.getEnglishName(), type);
		}
		
		for (TypeInfoModel type : types) {
			if(type.getPid() != 0){
				allType.get(type.getPid().toString()).addChildren(type);
			}
		}
		
		for (TypeInfoModel type : topTypes) {
			setChildrenIds(type);
		}
		
		
	}
	
	

	@Override
	public Integer insert(TypeInfoModel typeInfoModel) {
		int count = 0;
		TypeInfoModel parent = getTypeById(typeInfoModel.getPid());
		typeInfoModel.setOrder(parent.getChildren().size()+1);
		typeInfoModel.setStatus(1);
		typeInfoModel.setCreateTime(new Date());
		typeInfoModel.setUpdateTime(new Date());
		count = super.insert(typeInfoModel);
		return count;
	}

	@Override
	public Integer updateById(TypeInfoModel entity) {
		entity.setUpdateTime(new Date());
		int count = super.updateById(entity);
		return count;
	}

	@Override
	public Integer updateNULLById(TypeInfoModel entity) {
		entity.setUpdateTime(new Date());
		int count = super.updateNULLById(entity);
		return count;
	}

	@Override
	public Integer removeById(Integer id) {
		int count = super.removeById(id);
		return count;
	}

	@Override
	public Integer removeByIds(Integer[] ids) {
		int count = super.removeByIds(ids);
		return count;
	}

	@Override
	public List<TypeTree> getTypeTree(Integer id,boolean expanded,boolean hideDisableMenus) {
		List<TypeTree> typeTrees = new ArrayList<TypeTree>();
		List<TypeInfoModel> types = getChildrenTypeById(id);
		for (TypeInfoModel type : types) {
			TypeTree typeTree = new TypeTree(type.getId().toString(), type.getName());
			boolean showNode = true;
			if(hideDisableMenus && type.getStatus()!=1){
				showNode = false;
			}
			if(showNode && type.getPid()!=null){  //过滤掉父节点不存在的脏数据
				List<TypeTree> children = getTypeTree(type.getId(),expanded,hideDisableMenus);
				if(children.size()>0){
					typeTree.setChildren(children);
				}
				typeTree.setExpanded(expanded);
				typeTrees.add(typeTree);
				
			}	
		}
		return typeTrees;
	}

	@Override
	public TypeInfoModel getTypeById(Integer id) {
		TypeInfoModel type= allType.get(id.toString());
		return type;
	}
	
	@Override
	public TypeInfoModel getTypeByEnglishName(String englishName) {
		TypeInfoModel type= allEnglishType.get(englishName);
		return type;
	}

	@Override
	public Integer getTypeId(String englishName, Integer id) {
		if(StringUtils.isNotBlank(englishName)){
			TypeInfoModel parent= allEnglishType.get(englishName);
			if(parent != null){
				if(id != null){
					if(getAncestorsType(parent.getId(),id)){
						return id;
					}else{
						return parent.getId();
					}
				}else{
					return parent.getId();
				}
			}
		}
		return null;
	}
	
	@Override
	public List<TypeInfoModel> getChildrenTypeById(Integer id){
		List<TypeInfoModel> types = null;
		
		if(id != null && id == 0){
			types = topTypes;
		}else{
			TypeInfoModel type= getTypeById(id);
			if(type != null){
				types = type.getChildren();
			}
		}
		
		
		return types;
	}
	
	@Override
	public List<TypeInfoModel> getOnlyChildrenTypeById(Integer id){
		List<TypeInfoModel> types = null;
		
		if(id != null && id == 0){
			types = topTypes;
		}else{
			TypeInfoModel parent= getTypeById(id);
			if(parent != null){
				List<TypeInfoModel> children = parent.getChildren();
				if(children.size()>0){
					types = new ArrayList<>();
					for (TypeInfoModel type : children) {
						TypeInfoModel newType = new TypeInfoModel();
						BeanUtils.copyProperties(type,newType);
						newType.setChildrenIds(null);
						newType.setChildren(null);
						types.add(newType);
					}
				}
			}
		}
		
		return types;
	}


	@Override
	public Map<String, String> getAllTypeToMap(String englishName) {
		TypeInfoModel parent= getTypeByEnglishName(englishName);
		return getAllTypeToMap(parent);
	}
	
	@Override
	public Map<String, String> getAllTypeToMap(Integer id){
		TypeInfoModel parent= getTypeById(id);
		return getAllTypeToMap(parent);
	}
	
	private Map<String, String> getAllTypeToMap(TypeInfoModel parent){
		Map<String, String> types = new TreeMap<>();
		if(parent != null && parent.getId() != null){
			types.put(parent.getId().toString(), parent.getName());
			List<Integer> ids = parent.getChildrenIds();
			for (Integer tyoeId : ids) {
				TypeInfoModel type= getTypeById(tyoeId);
				types.put(tyoeId.toString(), type.getName());
			}
		}
		
		return types;
	}
	
	@Override
	public Map<String, String> getAllChildrenTypeToMap(Integer id){
		Map<String, String> types = new TreeMap<>();
		TypeInfoModel parent= getTypeById(id);
		List<Integer> ids = parent.getChildrenIds();
		for (Integer tyoeId : ids) {
			TypeInfoModel type= getTypeById(tyoeId);
			types.put(tyoeId.toString(), type.getName());
		}
		return types;
	}
	
	@Override
	public Map<String, String> getAllChildrenTypeToMap(String englishName){
		Map<String, String> types = new TreeMap<>();
		TypeInfoModel parent= getTypeByEnglishName(englishName);
		List<Integer> ids = parent.getChildrenIds();
		for (Integer tyoeId : ids) {
			TypeInfoModel type= getTypeById(tyoeId);
			types.put(tyoeId.toString(), type.getName());
		}
		return types;
	}
	
	
	@Override
	public Response getAllChildrenType(TypeRequest requset){
		ResponseBodyToOne response = new ResponseBodyToOne();
		if(requset.getPid() == null){
			throw new RequiredException("pid");
		}
		Map<String, String> childrens = getAllChildrenTypeToMap(requset.getPid());
		response.setData(childrens);
		return response;
		
	}
	//------------------请在此添加自定义方法（结束）------------------
	
	
	private void setChildrenIds(TypeInfoModel type){
		if(type != null){
			if(type.getChildren().size()>0){
				for (TypeInfoModel children : type.getChildren()) {
					setChildrenIds(children);
					type.addChildrenIds(children.getId());
					type.addChildrenIds(children.getChildrenIds());
				}
			}
		}
	}
	
	/**
	 * <p>判断是不是type 是不是属于祖先类</p>  
	 * @param ancestorsId 祖先类的Id
	 * @param id		
	 * @return   
	 * 创建人：邓强   <br>
	 * 创建时间：2017年11月8日 上午10:45:13    <br>
	 */
	private boolean getAncestorsType(Integer ancestorsId,Integer id){
		if(id == null || ancestorsId == null){
			return false;
		}
		TypeInfoModel children= allType.get(id.toString());
		if(children == null){
			return false;
		}
		if(id == ancestorsId || children.getPid().equals(ancestorsId)){
			return true;
		}else if(children.getPid() == 0){
			return false;
		}else{
			return getAncestorsType(ancestorsId, children.getPid());
		}
	}
}